package com.crazymakercircle.designmodel.masterworker;

import com.crazymakercircle.util.Print;
import com.crazymakercircle.util.ThreadUtil;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicLong;

/**
 * 8.2.1 Master-Worker 模式的参考实现
 */
public class MasterWorkerTest {

    //简单任务
    static class SimpleTask extends Task<Integer> {
        @Override
        protected Integer doExecute() {
            Print.tcfo("task " + getId() + " is done ");
            return getId();
        }
    }

    public static void main(String[] args) {
        //任务处理结果集
        Map<String, Integer> resultMap = new ConcurrentHashMap<>();
        //保持最终的和
        AtomicLong sum = new AtomicLong(0);

        // 结果类, 计算汇总回调和打印逻辑在里面
        IntegerResult integerResult = new IntegerResult(resultMap, sum);

        //创建Master ，包含四个worker，并启动master的执行线程
        Master<SimpleTask, Integer> master = new Master<>(4);

        //定期向master提交任务
        ThreadUtil.scheduleAtFixedRate(() -> {
                    SimpleTask task = new SimpleTask();
                    // 设置task的回调函数
                    task.setResultAction(integerResult:: resultCallBack);
                    master.submit(task);
                },
                2, TimeUnit.SECONDS);

        //定期从result提取结果
        ThreadUtil.scheduleAtFixedRate(
                () -> integerResult.printResult(),
                5, TimeUnit.SECONDS);
    }

}
